package handler

import (
	"context"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/logger"
	"yanxue_ai_go/pkg/common/response"
	"yanxue_ai_go/services/agent/internal/llm"
)

// ChatHandler AI问答处理器
type ChatHandler struct {
	openAIService *llm.OpenAIService
}

// NewChatHandler 创建AI问答处理器
func NewChatHandler() *ChatHandler {
	// 初始化OpenAI服务
	openAIService, err := llm.NewOpenAIService()
	if err != nil {
		logger.Logger.Error("Failed to initialize OpenAI service", zap.Error(err))
		return &ChatHandler{}
	}

	return &ChatHandler{
		openAIService: openAIService,
	}
}

// ChatRequest AI问答请求结构
type ChatRequest struct {
	Question string `json:"question" binding:"required"`
}

// ChatResponse AI问答响应结构
type ChatResponse struct {
	Question string `json:"question"`
	Answer   string `json:"answer"`
	Model    string `json:"model"`
}

// Chat AI问答接口
func (h *ChatHandler) Chat(c *gin.Context) {
	var req ChatRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	// 检查OpenAI服务是否可用
	if h.openAIService == nil {
		response.InternalServerError(c, "OpenAI service not available")
		return
	}

	// 调用AI问答
	ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
	defer cancel()

	answer, err := h.openAIService.Ask(ctx, req.Question)
	if err != nil {
		logger.Logger.Error("Failed to get AI response",
			zap.Error(err),
			zap.String("question", req.Question))
		response.InternalServerError(c, fmt.Sprintf("Failed to get AI response: %v", err))
		return
	}

	// 返回问答结果
	response.Success(c, ChatResponse{
		Question: req.Question,
		Answer:   answer,
		Model:    h.openAIService.GetModel(),
	})
}

// GetConfig 获取当前AI配置信息
func (h *ChatHandler) GetConfig(c *gin.Context) {
	if h.openAIService == nil {
		response.InternalServerError(c, "OpenAI service not available")
		return
	}

	response.Success(c, gin.H{
		"model":     h.openAIService.GetModel(),
		"available": true,
		"service":   "OpenAI",
	})
}
